//
//  PAWKWebViewCell.m
//  PilotSeries
//
//  Created by 黄立强 on 16/7/5.
//  Copyright © 2016年 leon.huang. All rights reserved.
//

#import "PAWKWebViewCell.h"
#import "Masonry.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "ChartConfig.h"

@interface PAWKWebViewCell () <WKNavigationDelegate,WKUIDelegate>
@end
@implementation PAWKWebViewCell

+ (instancetype) cellWithCollection:(UICollectionView *)collectionView forIndexPath:indexPath{
    
    static NSString *identify = @"wkwebviewcell";
    PAWKWebViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    LOGMETHOD
    LOG(@"PAWKWebViewCell instancetype:%@",cell)
    return cell;
}

-(id)initWithFrame:(CGRect)frame{
    LOGMETHOD
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        NSString *js = @"document.documentElement.style.webkitUserSelect='none';";
        WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        [config.userContentController addUserScript:script];
        self.webView = [[WKWebView alloc] initWithFrame:frame configuration:config];
        self.webView.backgroundColor = [UIColor clearColor];
        self.webView.scrollView.showsHorizontalScrollIndicator = NO;
        self.webView.scrollView.showsVerticalScrollIndicator = NO;
        self.webView.scrollView.backgroundColor = [UIColor clearColor];
        self.webView.scrollView.subviews[0].backgroundColor = [UIColor clearColor];
        NSString *js2 = @"function sendMsg(msg){ window.webkit.messageHandlers.Bridge.postMessage(msg);}";
        WKUserScript *script2 = [[WKUserScript alloc] initWithSource:js2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [self.webView.configuration.userContentController addUserScript:script2];
//        [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Bridge"];
        [self.contentView addSubview:self.webView];
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.edges.equalTo(self.webView.superview).with.insets(UIEdgeInsetsZero);
        }];
        self.webView.userInteractionEnabled = NO;
        self.webView.scrollView.bounces = NO;
        self.webView.scrollView.scrollEnabled = NO;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [btn setTitle:@"x" forState:UIControlStateNormal];
//        [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//        [btn setTitle:@"x" forState:UIControlStateHighlighted];
        [btn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateHighlighted];
        [btn addTarget:self action:@selector(clickClose:) forControlEvents:UIControlEventTouchUpInside];
        self.closeBtn = btn;
        
        [self.contentView addSubview:self.closeBtn];
        
        [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.contentView).with.offset(-10);
            make.right.equalTo(self.contentView).with.offset(-10);
        }];
       
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resizeBtn:) name:@"resizeBtn" object:nil];
        
        self.webView.navigationDelegate = self;
//        self.webView.UIDelegate = self;
        
      
    }
    return self;
}


-(void)setUrl:(NSURL *)url{
    _url = url;
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    
}

//- (void)setChartConfig:(ChartConfig *)chartConfig{
//    _chartConfig = chartConfig;
//}

-(void) clickClose:(UIButton *) btn{
    
//    LOG(@"clickClose-------->");
    if([self.closeDelegate respondsToSelector:(@selector(webviewCellclickCloseItem:))]){
        [self.closeDelegate webviewCellclickCloseItem:self];
    }
}

-(void)resizeBtn:(NSNotification *)notice{
    [self.contentView bringSubviewToFront:self.closeBtn];
    
}
    
    
-(void) webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

    NSString *js2 = [NSString stringWithFormat:@"$(function(){processConfig(%@)});",[_chartConfig.config jk_JSONString]];
//    LOG(@"%@-->didFinishNavigation with config: %@",webView.title,js2)
    [self.webView evaluateJavaScript:js2 completionHandler:^(id _Nullable obj,NSError * _Nullable error) {
        
    }];
}

    
//-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
//    if([message.name isEqualToString:@"Bridge"]){
//        NSLog(@"扫一扫message");
//    }
//}
   
@end
